package com.gadarts.parashoot.player;

import java.util.List;

import com.gadarts.parashoot.GameModel;
import com.gadarts.parashoot.GameObject;
import com.gadarts.parashoot.GameView;
import com.gadarts.parashoot.Sprite;
import com.gadarts.parashoot.enemies.SoldierEnemy;
import com.gadarts.parashoot.utils.C;
import com.gadarts.parashoot.utils.Utils;

public class Bunker extends GameObject {

	private String reloadTimer;// The timer name of the gun reload.
	private String shootingTimer;// The timer name of the gun shooting.
	private boolean isShooting;

	public Bunker(GameModel model, GameView view, Sprite sprite, int x, int y,
			int depth) {
		super(model, view, sprite, x, y, 0, 0, depth, false);
		super.child = this;

		reloadTimer = Utils.setTimer(model, C.Player.RELOAD_TIMER_NAME);
		shootingTimer = Utils.setTimer(model, C.Player.SHOOTING_TIMER_NAME);
		setAnimation(C.Player.ANIMATION_SPEED, C.Player.ANIMATION_TIMER_NAME,
				false, false);
	}

	@Override
	public void update() {
		super.update();
		shoot();
	}

	private void shoot() {
		List<SoldierEnemy> soldiers = model.getSoldiers();

		if (isShooting)
			if (Utils.checkTiming(model, shootingTimer,
					C.Weapons.BunkerCannon.SHOOTING_TIME)) {
				isShooting = false;
				setSprite(view.getSprite(C.Player.BUNKER_IMAGE_NAME));
			}

		if (!soldiers.isEmpty()) {

			SoldierEnemy target = null;
			// Check if there are any soldiers on the ground.
			for (int i = 0; i < soldiers.size(); i++) {
				SoldierEnemy current = soldiers.get(i);
				if (current.isOnGround() && !current.isDead()) {
					target = current;
					break;
				}
			}

			if (target != null)
				if (Utils.checkTiming(model, reloadTimer, C.Player.RELOAD_TIME)) {

					if (target.getCenterX() < getCenterX())
						setSprite(view
								.getSprite(C.Player.BUNKER_SHOOTING_LEFT_IMAGE_NAME));
					else
						setSprite(view
								.getSprite(C.Player.BUNKER_SHOOTING_RIGHT_IMAGE_NAME));

					resetAnimation(C.Player.ANIMATION_SPEED, true);
					isShooting = true;
					Utils.updateTimer(model, shootingTimer);

					int hitTargetChances = random.nextInt(2);
					if (hitTargetChances == 0)
						target.setHealth(target.getHealth()
								- C.Weapons.BunkerCannon.DAMAGE);
				}
		}

	}

}
